import axios from "axios"
import cookies from "js-cookie"
import layer from '@/common/layer'
import config from '@/common/config'
import jquery from 'jquery';

let closeAjaxLayer = function () {
    // del ajax layer
    let layerArr = document.querySelectorAll('div.com-ajax-layer');
    layerArr.forEach((item) => {
        item.parentNode.removeChild(item);
    })
}

// in iphone,promise.finally can not work
// es6-promise in axios can not work
// so the only way is use interceptors
// don not use promise.finally any time

axios.interceptors.response.use(function (response) {
    closeAjaxLayer()
    return response
}, function (error) {
    closeAjaxLayer()
    return Promise.reject(error)
})

export default {
     host: config.host,
    // host: '',
    ajax: function (obj) {

        this.openAjaxLayer();

        let configObj = {
            baseURL: this.host,
            url: obj.url,
            method: (obj.type) ? obj.type.toLowerCase() : 'get',
            headers: {
                Authorization: `Bearer ${localStorage.token || cookies.get('Authorization')}`
            }
        };

        if (obj.type && obj.type.toLowerCase() === 'post') {
            configObj.data = obj.data;
        }

        if (obj.type && obj.type.toLowerCase() === 'get') {
            configObj.params = obj.data;
        }

        return axios.request(configObj).catch((error) => {
            if (obj.error) {
                obj.error(error.response.data)
            } else {
                console.log(error.response);
                switch (error.response.status) {
                    case 401:
                    case 403:
                        layer.open({
                            content: "您尚未登录或所在用户组没有权限，请重新登录",
                            btn: "去登录",
                            yes: () => {
                                window.location.href = `./login.html?redirect_uri=${encodeURIComponent(window.location.pathname)}`
                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        });
    },
    rjax: function (obj) {

        this.openAjaxLayer();

        let configObj = {
            baseURL: this.host,
            url: obj.url,
            method: (obj.type) ? obj.type.toLowerCase() : 'get'
        };

        if (obj.type && obj.type.toLowerCase() === 'post') {
            configObj.data = obj.data;
        }

        if (obj.type && obj.type.toLowerCase() === 'get') {
            configObj.params = obj.data;
        }

        return new Promise((resolve, reject) => {
            axios.request(configObj).then((res) => {
                if (res.data.code && parseInt(res.data.code) === 200) {
                    resolve(res.data || res.data.data || res.data.msg)
                } else {
                    reject(res)
                    return
                }
            }).catch((error) => {
                if (obj.error) {
                    obj.error(error.response.data)
                } else {
                    console.log(error.response);
                    switch (error.response.status) {
                        case 401:
                        case 403:
                            layer.open({
                                content: "您尚未登录或所在用户组没有权限，请重新登录",
                                btn: "去登录",
                                yes: () => {
                                    window.location.href = `./login.html?redirect_uri=${encodeURIComponent(window.location.pathname)}`
                                }
                            });
                            break;
                        default:
                            break;
                    }
                }
                reject(error)
            });

        })
    },
    getQuery: function () {
        // <<Professional JavaScript for Web Developers>> param BOM

        var qs = location.search.length > 0 ? location.search.substring(1) : '',
            args = {},
            items = qs.length ? qs.split('&') : [],
            item = null,
            name = null,
            value = null,
            i = 0,
            len = items.length

        for (let i = 0; i < len; i++) {
            item = items[i].split('=')
            name = decodeURIComponent(item[0])
            value = decodeURIComponent(item[1])

            if (name.length) {
                args[name] = value
            }
        }
        return args
    },
    fileUpload: function (file, cb) {
        // 这里修改文件上传大小限制
        // 注意修改提示语
        if (file.size > 5242880) {
            alert('图片大于4MB,请压缩后上传')
            return
        }
        var formData = new FormData()
        formData.append('file', file)
        // 让提示出现的代码放在这里
        // 
        jquery('body').append('<div class="global-upload-layer">图片上传中，请耐心等待...</div>')
        jquery.ajax({
            url: this.host + '/common/file/upload',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            cache: false,
            success: function (res) {
                // 让提示消失的代码放在这里
                // 
                jquery(".global-upload-layer").remove();
                cb(res)
            }
        })
    },
    obj2query: function (obj) {
        var queryString = ''
        for (let item in obj) {
            queryString += '&' + item + '=' + obj[item].toString()
        }
        queryString = '?' + queryString.substring(1)
        return queryString
    },
    logout: function () {
        localStorage.clear();
        window.location.href = `./login.html?redirect_uri=${encodeURIComponent(window.location.pathname)}`
    },
    openAjaxLayer: function () {
        // create a ajax layer
        let ajaxLayer = document.createElement('div');
        ajaxLayer.className = "com-ajax-layer";
        document.getElementsByTagName("body")[0].appendChild(ajaxLayer);
    },
    closeAjaxLayer: function () {
        // del ajax layer
        let layerArr = document.querySelectorAll('div.com-ajax-layer');
        layerArr.forEach((item) => {
            item.parentNode.removeChild(item);
        })
    },
    isWechat: function () {
        return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
    }
}